package com.neusoft.db;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.neusoft.utils.MyUtil;

public class DBProvider {
	/**
	 * 获取Mapper对象
	 * 
	 * @param <T>
	 * 
	 * @return Mapper对象
	 */
	public <T> T getMyMapper(Class<T> clazz) {
		T re_t = null;
		try {
			// 将mybatis的配置文件读取为输入流对象
			InputStream inConfigMybaits = MyUtil.class.getClassLoader().getResourceAsStream("config-mybatis.xml");
			// 将数据库配置文件读取为Properties
			Properties propDB = new Properties();
			// 加载配置文件
			propDB.load(MyUtil.class.getClassLoader().getResourceAsStream("db.properties"));

			// SqlSessionFactory的创建类
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			// 使用builder创建SqlSessionFactory类
			SqlSessionFactory factory = builder.build(inConfigMybaits, propDB);
			// 获取SqlSession 对象
			SqlSession sqlS = factory.openSession();
			// 获取mapper映射接口层
			re_t = sqlS.getMapper(clazz);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return re_t;
	}

	/**
	 * 获取SqlSession对象
	 * 
	 * @return SQLSession对象
	 */
	public SqlSession getSession() {
		SqlSession sqlS = null;
		try {
			// 将mybatis的配置文件读取为输入流对象
			InputStream inConfigMybaits = MyUtil.class.getClassLoader().getResourceAsStream("config-mybatis.xml");
			// 将数据库配置文件读取为Properties
			Properties propDB = new Properties();
			// 加载配置文件
			propDB.load(MyUtil.class.getClassLoader().getResourceAsStream("db.properties"));

			// SqlSessionFactory的创建类
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			// 使用builder创建SqlSessionFactory类
			SqlSessionFactory factory = builder.build(inConfigMybaits, propDB);
			// 获取SqlSession 对象
			sqlS = factory.openSession();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sqlS;
	}
}
